<template>
    <van-sticky>
        <van-nav-bar
            title="添加收货地址"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

    <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        :address-info="info"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDel"
    />

</template>

<script setup>
import { areaList } from '@vant/area-data';
const { proxy } = getCurrentInstance();

// 根据id获取到相关数据
const info = reactive({});
const addrid = ref(proxy.$route.query.addrid);

onBeforeMount(() => {
    getAddressInfo();
})

const getAddressInfo = async () => {
    let params = {
        busid:proxy.$business.value.id,
        addrid:addrid.value
    }

    let result = await proxy.$post({
        url:'/business/address/info',
        params
    })

    if(result.code === 1)
    {
        let Info = result.data;

        // 通过合并更新数据
        Object.assign(info,{
            name:Info.consignee,
            tel:Info.mobile,
            areaCode:Info.district ? Info.district : (Info.city ? Info.city : Info.province),
            addressDetail:Info.address,
            isDefault:Info.status == 1 ? true : false
        })
    }
}

const onSave = async (values) => {
    let params = {
        busid:proxy.$business.value.id,
        id:addrid.value,
        consignee:values.name,
        mobile:values.tel,
        code:values.areaCode,
        address:values.addressDetail,
        status:values.isDefault === true ? 1 : 0
    }

    let result = await proxy.$post({
        url:'/business/address/edit',
        params
    })

    if(result.code === 1)
    {
        proxy.$successNotify({
            message:result.msg,
            onClose:() => {
                onBack();
            }
        })

        return false;
    }else{
        proxy.$warnNotify(result.msg);

        return false;
    }
}

const onDel = () => {
    proxy.$showConfirm({
        title:'删除收货地址',
        message:'是否确认删除该收货地址？'
    }).then(async () => {
        let params = {
            busid:proxy.$business.value.id,
            addrid:addrid.value
        }

        let result = await proxy.$post({
            url:'/business/address/del',
            params
        });

        if(result.code === 1)
        {
            proxy.$successNotify({
                message:result.msg,
                onClose:() => {
                    onBack();
                }
            })

            return false;
        }else{
            proxy.$warnNotify(result.msg);

            return false;
        }
    }).catch((err) => {
        
    });
}

const onBack = () => proxy.$router.back();
</script>